package com.xqboss.common.utils;

import java.lang.management.ManagementFactory;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.temporal.ChronoUnit;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import org.apache.commons.lang3.time.DateFormatUtils;

/**
 * 时间工具类
 *
 * @author Administrator
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
    public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";

    public static String YYYY_MM_DD = "yyyy-MM-dd";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

    /**
     * 获取当前Date型日期
     *
     * @return Date() 当前日期
     */
    public static Date getNowDate() {
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     *
     * @return String
     */
    public static String getDate() {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static final String getTime() {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static final String dateTimeNow() {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeNow(final String format) {
        return parseDateToStr(format, new Date());
    }

    public static final String dateTime(final Date date) {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static final String parseDateToStr(final String format, final Date date) {
        return new SimpleDateFormat(format).format(date);
    }

    public static final Date dateTime(final String format, final String ts) {
        try {
            return new SimpleDateFormat(format).parse(ts);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 根据TimeUnit增加指定日期的的时间
     *
     * @param date     要增加的日期
     * @param timeUnit 增加的日历字段（只能取 DAYS 到 MILLISECONDS 之间的枚举，否则报错）
     * @param value    增加的值(当值为负数时表示减少)
     * @return
     * @author jianguo.xu
     */
    public static Date add(Date date, TimeUnit timeUnit, int value) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(calField(timeUnit), value);
        return cal.getTime();
    }


    /**
     * 增加指定天数，不含周六、周天
     *
     * @param startDate      要增加的日期
     * @param expirationDays 增加的天数
     * @return 不含周六、周天的增加天数后的日期
     */
    public static Date add(Date startDate, int expirationDays) {
        return add(startDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime(), expirationDays);
    }

    public static Date add(LocalDateTime startDate, int expirationDays) {
        LocalDateTime expirationDate = startDate;
        int addedDays = 0;
        while (addedDays < expirationDays) {
            expirationDate = expirationDate.plusDays(1);
            if (expirationDate.getDayOfWeek() != DayOfWeek.SATURDAY && expirationDate.getDayOfWeek() != DayOfWeek.SUNDAY) {
                addedDays++;
            }
        }
        return Date.from(expirationDate.atZone(ZoneId.systemDefault()).toInstant());
    }

    /**
     * 日历字段
     *
     * @param timeUnit 时间单位
     * @return int
     */
    private static int calField(TimeUnit timeUnit) {
        int field = 0;
        if (timeUnit == TimeUnit.YEAR)
            field = Calendar.YEAR;
        else if (timeUnit == TimeUnit.MONTH)
            field = Calendar.MONTH;
        else if (timeUnit == TimeUnit.WEEK_OF_YEAR)
            field = Calendar.WEEK_OF_YEAR;
        else if (timeUnit == TimeUnit.WEEK_OF_MONTH)
            field = Calendar.WEEK_OF_MONTH;
        else if (timeUnit == TimeUnit.DAY_OF_WEEK)
            field = Calendar.DAY_OF_WEEK;
        else if (timeUnit == TimeUnit.DAYS)
            field = Calendar.DAY_OF_YEAR;
        else if (timeUnit == TimeUnit.DAY_OF_MONTH)
            field = Calendar.DAY_OF_MONTH;
        else if (timeUnit == TimeUnit.HOURS)
            field = Calendar.HOUR_OF_DAY;
        else if (timeUnit == TimeUnit.MINUTES)
            field = Calendar.MINUTE;
        else if (timeUnit == TimeUnit.SECONDS)
            field = Calendar.SECOND;
        else if (timeUnit == TimeUnit.MILLISECONDS)
            field = Calendar.MILLISECOND;
        else
            throw new RuntimeException("timeUnit error");
        return field;
    }

    /**
     * 获取到过期时间的有效，
     *
     * @param hireTime      过期日期
     * @param isContainEnd  是否包含结束日期
     * @param isContainWeek 是否包括周六和周日
     * @return 获取到过期时间的有效天数
     */
    public static long getEffectiveDay(Date hireTime, boolean isContainEnd, boolean isContainWeek) {
        LocalDateTime startDateTime = LocalDateTime.now();
        LocalDateTime endDateTime = hireTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();;

        long days = ChronoUnit.DAYS.between(startDateTime.toLocalDate(), endDateTime.toLocalDate()) + (isContainEnd ? 1 : 0); // 包括结束日期
        if (isContainWeek) return days;
        long businessDays = 0;
        for (LocalDateTime dateTime = startDateTime; !dateTime.toLocalDate().isAfter(endDateTime.toLocalDate()); dateTime = dateTime.plusDays(1)) {
            DayOfWeek dayOfWeek = dateTime.getDayOfWeek();
            if (dayOfWeek != DayOfWeek.SATURDAY && dayOfWeek != DayOfWeek.SUNDAY) {
                businessDays++;
            }
        }
        long day = businessDays -1;
        return day<0 ? 0:day ;
    }

    /**
     * 获取到过期时间的有效，
     *
     * @param end      过期日期
     * @param isContainWeek 是否排除周六和周日
     * @return 获取到过期时间的有效天数
     */
    public static long getEffectiveHour(Date end,boolean isContainWeek) {
        Date start = new Date();
        //比较 end 和 start 的大小，如果 end 小于 start，则相差天数为负数，则返回 0
        if (end.before(start)) {
            return 0;
        }
        long hour = DateUtil.between(start, end, DateUnit.HOUR);//两日期相差多少小时
        if (!isContainWeek) {
            return hour;
        }else{
            long days = 0;//周六周末总计天数
            for (Date date = start; date.before(end); date = DateUtil.offsetDay(date, 1)) {
                int dayOfWeek = DateUtil.dayOfWeek(date);
                if (dayOfWeek == 1 ||  dayOfWeek == 7) { // 排除周六和周日
                    days++;
                }
            }
            return hour - days * 24;
        }
    }



    /**
     * 时间单位
     *
     * @author zhaopengfei
     * @date 2023/12/07
     */
    public enum TimeUnit {
        YEAR, MONTH, WEEK_OF_YEAR, WEEK_OF_MONTH, DAY_OF_WEEK, DAYS, DAY_OF_MONTH, HOURS, MINUTES, SECONDS, MILLISECONDS
    }

    /**
     * 两个日期相减得到相差的分钟数
     *
     * @param date
     * @param other
     * @return
     */
    public static long subtractMin(Date date, Date other) {
        return subtractSecond(date, other) / (60);
    }

    /**
     * 分钟转小时
     *
     * @param min
     * @return
     */
    public static BigDecimal minToHour(int min) {
        if (min <= 0) {
            return BigDecimal.ZERO;
        }
        BigDecimal dividend = new BigDecimal(min);
        BigDecimal divisor = new BigDecimal("60");
        BigDecimal hour = dividend.divide(divisor, 2, RoundingMode.HALF_UP);
        // 由于定时任务是每小时结算一次空投，如果时间大于了一小时，则说明开始生产时间有问题，那么就返回1小时
        if (hour.compareTo(BigDecimal.ONE) > 0){
            return BigDecimal.ONE;
        }
        return hour;
    }

    /**
     * 两个日期相减得到相差的秒数
     *
     * @param date
     * @param other
     * @return
     */
    public static long subtractSecond(Date date, Date other) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        long dateTimeInMillis = calendar.getTimeInMillis();
        Calendar otherCalendar = Calendar.getInstance();
        otherCalendar.setTime(other);
        long otherTimeInMillis = otherCalendar.getTimeInMillis();
        return (dateTimeInMillis - otherTimeInMillis) / (1000);
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTime() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str) {
        if (str == null) {
            return null;
        }
        try {
            return parseDate(str.toString(), parsePatterns);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate() {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算相差天数
     */
    public static int differentDaysByMillisecond(Date date1, Date date2) {
        return Math.abs((int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24)));
    }

    /**
     * 计算时间差
     *
     * @param endDate   最后时间
     * @param startTime 开始时间
     * @return 时间差（天/小时/分钟）
     */
    public static String timeDistance(Date endDate, Date startTime) {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - startTime.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }

    /**
     * 增加 LocalDateTime ==> Date
     */
    public static Date toDate(LocalDateTime temporalAccessor) {
        ZonedDateTime zdt = temporalAccessor.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }

    /**
     * 增加 LocalDate ==> Date
     */
    public static Date toDate(LocalDate temporalAccessor) {
        LocalDateTime localDateTime = LocalDateTime.of(temporalAccessor, LocalTime.of(0, 0, 0));
        ZonedDateTime zdt = localDateTime.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }
}
